package boardInfo

import (
	"fmt"
	"util"
)

const (
	reqSmallFileSize = 38
	resSmallFileSize = 46
)

// 小文件请求消息
type stReqSmallFile struct {
	dwRequestId int32
	wTypeId     uint16
	szFileName  string
	dwReserved  [4]int32
}

func (st *stReqSmallFile) EnCode() []byte {
	var b []byte
	b = append(b, util.Base2Byte(st.dwRequestId)...)
	b = append(b, util.Base2Byte(st.wTypeId)...)

	var fileName [16]byte
	num := len(st.szFileName)
	if num > 16 {
		num = 16
	}
	for idx := 0; idx < num; idx++ {
		fileName[idx] = st.szFileName[idx]
	}
	b = append(b, fileName[0:]...)

	for idx := 0; idx < 4; idx++ {
		b = append(b, util.Base2Byte(st.dwReserved[idx])...)
	}

	return b
}

func (st *stReqSmallFile) DeCode(b []byte) error {
	num := len(b)
	if num < reqSmallFileSize {
		return fmt.Errorf("stRequestSmallFile Decode date size too small")
	}

	pos := 0
	bt := b[pos : pos+4]
	pos += 4
	st.dwRequestId = util.Byte2Base[int32](bt)

	bt = b[pos : pos+2]
	pos += 2
	st.wTypeId = util.Byte2Base[uint16](bt)

	bt = b[pos : pos+16]
	pos += 16
	num = 0
	for idx, v := range bt {
		if v == 0 {
			num = idx
			break
		}
	}
	st.szFileName = string(bt[0:num])

	for idx := 0; idx < 4; idx++ {
		bt = b[pos : pos+4]
		pos += 4
		st.dwReserved[idx] = util.Byte2Base[int32](bt)
	}

	return nil
}

// 小文件响应消息
type stResSmallFile struct {
	dwRequestId uint32
	wTypeId     uint16
	szFileName  string //占用16个字节
	bFindFile   uint32
	dwSize      uint32
	dwReserved  [4]int32
	data        []byte
}

func (st *stResSmallFile) EnCode() []byte {
	var b []byte
	return b
}

func (st *stResSmallFile) DeCode(b []byte) error {
	num := len(b)
	if num < resSmallFileSize {
		return fmt.Errorf("stResSmallFile Decode date size too small")
	}

	pos := 0
	bt := b[pos : pos+4]
	pos += 4
	st.dwRequestId = util.Byte2Base[uint32](bt)

	bt = b[pos : pos+2]
	pos += 2
	st.wTypeId = util.Byte2Base[uint16](bt)

	//解析文件名
	bt = b[pos : pos+16]
	pos += 16
	num = 0
	for idx, v := range bt {
		if v == 0 {
			num = idx
			break
		}
	}
	st.szFileName = string(bt[0:num])

	bt = b[pos : pos+4]
	pos += 4
	st.bFindFile = util.Byte2Base[uint32](bt)

	bt = b[pos : pos+4]
	pos += 4
	st.dwSize = util.Byte2Base[uint32](bt)

	for idx := 0; idx < 4; idx++ {
		bt = b[pos : pos+4]
		pos += 4
		st.dwReserved[idx] = util.Byte2Base[int32](bt)
	}
	st.data = b[pos:]

	//判断负载数据包是否正确
	if len(st.data) != int(st.dwSize) {

	}

	return nil
}

func btStrPos(bt []byte) int {
	num := 0
	for idx, v := range bt {
		if v == 0 {
			num = idx
			break
		}
	}
	return num
}

// 包头
type StPacketHead struct {
	WPid      uint16 //包ID
	DwBodyLen uint32 //包体字节数
}

const CHeadSize = 6

func (s *StPacketHead) EnCode() []byte {
	var b []byte
	b = append(b, util.Uint16ToByte(s.WPid)...)
	b = append(b, util.Uint32ToByte(s.DwBodyLen)...)
	return b
}

func (s *StPacketHead) DeCode(b []byte) {
	s.WPid = util.Byte2Uint16(b[:2])
	s.DwBodyLen = util.Byte2Uint32(b[2:6])
}

type IEnCode interface {
	EnCode() []byte
}

type IDeCode interface {
	DeCode(b []byte) error
}
